package com.mybatis.util;

import org.springframework.data.domain.Sort;

import java.util.regex.Pattern;

public class SqlUtil {
    /**
     * 排序表达式
     * 又是一个提升的知识点,第二个参数是忽略大小写
     */
    private static final Pattern ORDER_BY = Pattern.compile(".*order\\s+by\\s+.*", Pattern.CASE_INSENSITIVE);

    public static String applySorting(String sql, Sort sort) {
        if (null==sort || !sort.iterator().hasNext())
        {
            return  sql;
        }
        StringBuilder builder = new StringBuilder(sql);
        if (!ORDER_BY.matcher(sql).matches())
        {
            builder.append(" order by ");
        }
        else {
            builder.append(", ");
        }
        for (Sort.Order order : sort)
        {
            builder.append(getOrderClause(order)).append(", ");
        }
        builder.delete(builder.length() - 2, builder.length());
        return builder.toString();

    }

    //这边将排序属性名转化成了小写，感觉数据库不区分啊
    private static String getOrderClause(Sort.Order order) {
        String property = order.getProperty();
        String wrapped = order.isIgnoreCase()? property.toLowerCase():property;

        return String.format("%s %s",wrapped,toSqlDiretion(order));
    }

    private static String toSqlDiretion(Sort.Order order) {
        return order.getDirection().name().toLowerCase();
    }
}
